window.TextDeduplicatorRenderer = class TextDeduplicatorRenderer {
    static getHTML() {
        return `
            <div class="tool-content">
                <h2 class="text-3xl font-bold text-gray-800 mb-6 flex items-center">
                    <i data-feather="list" class="mr-3"></i>
                    文本去重排序工具
                </h2>
                
                <div class="bg-blue-50 border-l-4 border-blue-400 p-4 mb-6">
                    <p class="text-blue-800">
                        <i data-feather="info" class="inline w-4 h-4 mr-1"></i>
                        支持普通文本和CSV文件的去重排序处理，适合Excel数据清理和日志文件整理
                    </p>
                </div>

                <!-- 模式选择 -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">处理模式</label>
                    <div class="flex space-x-4">
                        <label class="flex items-center">
                            <input type="radio" name="mode" value="text" class="mr-2" checked>
                            <span>普通文本模式</span>
                        </label>
                        <label class="flex items-center">
                            <input type="radio" name="mode" value="csv" class="mr-2">
                            <span>CSV模式（按列去重）</span>
                        </label>
                    </div>
                </div>

                <!-- 输入区域 -->
                <div class="grid md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <div class="flex justify-between items-center mb-2">
                            <label class="block text-sm font-medium text-gray-700">输入文本</label>
                            <button id="clear-input" class="text-red-600 hover:text-red-800 text-sm flex items-center">
                                <i data-feather="trash-2" class="w-4 h-4 mr-1"></i>
                                清空
                            </button>
                        </div>
                        <textarea 
                            id="text-input" 
                            placeholder="粘贴需要去重的文本内容，每行一条数据..."
                            class="w-full h-40 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                        ></textarea>
                        <div class="text-sm text-gray-600 mt-1">
                            <span id="input-stats">行数: 0</span>
                        </div>
                    </div>

                    <div>
                        <div class="flex justify-between items-center mb-2">
                            <label class="block text-sm font-medium text-gray-700">输出结果</label>
                            <button id="copy-result" class="bg-green-600 hover:bg-green-700 text-white text-sm px-3 py-1 rounded flex items-center">
                                <i data-feather="copy" class="w-4 h-4 mr-1"></i>
                                复制
                            </button>
                        </div>
                        <textarea 
                            id="text-output" 
                            readonly
                            placeholder="处理结果将显示在这里..."
                            class="w-full h-40 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50 resize-none"
                        ></textarea>
                        <div class="text-sm text-gray-600 mt-1">
                            <span id="output-stats">等待处理...</span>
                        </div>
                    </div>
                </div>

                <!-- 处理选项 -->
                <div class="grid md:grid-cols-2 gap-6 mb-6">
                    <!-- 普通文本选项 -->
                    <div id="text-options" class="space-y-4">
                        <h3 class="text-lg font-semibold text-gray-800">文本处理选项</h3>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">排序方式</label>
                            <select id="sort-order" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="asc">升序排列</option>
                                <option value="desc">降序排列</option>
                                <option value="none">不排序（保持原顺序）</option>
                            </select>
                        </div>

                        <div class="space-y-2">
                            <label class="flex items-center">
                                <input type="checkbox" id="case-sensitive" class="mr-2" checked>
                                <span class="text-sm">区分大小写</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" id="remove-empty" class="mr-2" checked>
                                <span class="text-sm">移除空行</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" id="trim-whitespace" class="mr-2" checked>
                                <span class="text-sm">去除行首尾空白字符</span>
                            </label>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">分隔符</label>
                            <select id="delimiter" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="\\n">换行符（默认）</option>
                                <option value=",">逗号</option>
                                <option value=";">分号</option>
                                <option value="\\t">制表符</option>
                                <option value=" ">空格</option>
                                <option value="|">竖线</option>
                            </select>
                        </div>
                    </div>

                    <!-- CSV选项 -->
                    <div id="csv-options" class="space-y-4" style="display: none;">
                        <h3 class="text-lg font-semibold text-gray-800">CSV处理选项</h3>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">去重依据列（从0开始）</label>
                            <input type="number" id="column-index" value="0" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <div class="text-xs text-gray-500 mt-1">例如：0表示第一列，1表示第二列</div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">排序方式</label>
                            <select id="csv-sort-order" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="asc">升序排列</option>
                                <option value="desc">降序排列</option>
                                <option value="none">不排序（保持原顺序）</option>
                            </select>
                        </div>

                        <div class="space-y-2">
                            <label class="flex items-center">
                                <input type="checkbox" id="csv-case-sensitive" class="mr-2" checked>
                                <span class="text-sm">区分大小写</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" id="has-header" class="mr-2" checked>
                                <span class="text-sm">包含标题行</span>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- 处理按钮 -->
                <div class="flex justify-center mb-6">
                    <button id="process-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="filter" class="w-4 h-4 mr-2"></i>
                        开始处理
                    </button>
                </div>

                <!-- 统计信息 -->
                <div id="stats-section" class="bg-gray-50 rounded-lg p-4" style="display: none;">
                    <h3 class="text-lg font-semibold text-gray-800 mb-3">处理统计</h3>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
                        <div class="bg-white rounded-lg p-3">
                            <div class="text-2xl font-bold text-blue-600" id="original-count">0</div>
                            <div class="text-sm text-gray-600">原始行数</div>
                        </div>
                        <div class="bg-white rounded-lg p-3">
                            <div class="text-2xl font-bold text-green-600" id="unique-count">0</div>
                            <div class="text-sm text-gray-600">去重后行数</div>
                        </div>
                        <div class="bg-white rounded-lg p-3">
                            <div class="text-2xl font-bold text-red-600" id="removed-count">0</div>
                            <div class="text-sm text-gray-600">移除重复行</div>
                        </div>
                        <div class="bg-white rounded-lg p-3">
                            <div class="text-2xl font-bold text-purple-600" id="duplicate-rate">0%</div>
                            <div class="text-sm text-gray-600">重复率</div>
                        </div>
                    </div>
                </div>

                <!-- 下载按钮 -->
                <div id="download-section" class="text-center mt-6" style="display: none;">
                    <button id="download-btn" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center mx-auto">
                        <i data-feather="download" class="w-4 h-4 mr-2"></i>
                        下载结果
                    </button>
                </div>
            </div>
        `;
    }

    static init() {
        const textInput = document.getElementById('text-input');
        const textOutput = document.getElementById('text-output');
        const processBtn = document.getElementById('process-btn');
        const clearBtn = document.getElementById('clear-input');
        const copyBtn = document.getElementById('copy-result');
        const downloadBtn = document.getElementById('download-btn');
        const inputStats = document.getElementById('input-stats');
        const outputStats = document.getElementById('output-stats');

        // 模式切换
        const modeRadios = document.querySelectorAll('input[name="mode"]');
        const textOptions = document.getElementById('text-options');
        const csvOptions = document.getElementById('csv-options');

        modeRadios.forEach(radio => {
            radio.addEventListener('change', (e) => {
                if (e.target.value === 'text') {
                    textOptions.style.display = 'block';
                    csvOptions.style.display = 'none';
                } else {
                    textOptions.style.display = 'none';
                    csvOptions.style.display = 'block';
                }
            });
        });

        // 输入统计更新
        const updateInputStats = DevToolsUtils.debounce(() => {
            const lines = textInput.value.split('\n').filter(line => line.trim() !== '');
            inputStats.textContent = `行数: ${lines.length}`;
        }, 300);

        textInput.addEventListener('input', updateInputStats);

        // 清空输入
        clearBtn.addEventListener('click', () => {
            textInput.value = '';
            textOutput.value = '';
            updateInputStats();
            outputStats.textContent = '等待处理...';
            document.getElementById('stats-section').style.display = 'none';
            document.getElementById('download-section').style.display = 'none';
        });

        // 处理文本
        processBtn.addEventListener('click', () => {
            const text = textInput.value.trim();
            if (!text) {
                DevToolsUtils.showToast('请输入要处理的文本', 'error');
                return;
            }

            DevToolsUtils.addLoading(processBtn, '处理中...');
            
            setTimeout(() => {
                try {
                    const mode = document.querySelector('input[name="mode"]:checked').value;
                    let result;

                    if (mode === 'text') {
                        // 普通文本模式
                        const delimiter = document.getElementById('delimiter').value.replace('\\n', '\n').replace('\\t', '\t');
                        const options = {
                            sortOrder: document.getElementById('sort-order').value,
                            caseSensitive: document.getElementById('case-sensitive').checked,
                            removeEmptyLines: document.getElementById('remove-empty').checked,
                            trimWhitespace: document.getElementById('trim-whitespace').checked,
                            delimiter: delimiter
                        };
                        result = TextDeduplicator.deduplicate(text, options);
                    } else {
                        // CSV模式
                        const options = {
                            columnIndex: parseInt(document.getElementById('column-index').value) || 0,
                            sortOrder: document.getElementById('csv-sort-order').value,
                            caseSensitive: document.getElementById('csv-case-sensitive').checked,
                            hasHeader: document.getElementById('has-header').checked
                        };
                        result = TextDeduplicator.deduplicateByColumn(text, options);
                    }

                    if (result.success) {
                        textOutput.value = result.data.result;
                        outputStats.textContent = `行数: ${result.data.stats.uniqueCount}`;
                        
                        // 显示统计信息
                        document.getElementById('original-count').textContent = result.data.stats.originalCount;
                        document.getElementById('unique-count').textContent = result.data.stats.uniqueCount;
                        document.getElementById('removed-count').textContent = result.data.stats.removedCount;
                        document.getElementById('duplicate-rate').textContent = result.data.stats.duplicateRate + '%';
                        document.getElementById('stats-section').style.display = 'block';
                        document.getElementById('download-section').style.display = 'block';
                        
                        DevToolsUtils.showToast('文本处理完成！', 'success');
                    } else {
                        DevToolsUtils.showToast(result.error, 'error');
                        textOutput.classList.add('error-border');
                        setTimeout(() => {
                            textOutput.classList.remove('error-border');
                        }, 3000);
                    }
                } catch (error) {
                    DevToolsUtils.showToast('处理过程中发生错误', 'error');
                    console.error('Text deduplication error:', error);
                } finally {
                    DevToolsUtils.removeLoading(processBtn, '开始处理');
                }
            }, 100);
        });

        // 复制结果
        copyBtn.addEventListener('click', async () => {
            if (!textOutput.value.trim()) {
                DevToolsUtils.showToast('没有可复制的内容', 'error');
                return;
            }

            const success = await DevToolsUtils.copyToClipboard(textOutput.value);
            if (success) {
                DevToolsUtils.showToast('已复制到剪贴板', 'success');
                textOutput.classList.add('success-border');
                setTimeout(() => {
                    textOutput.classList.remove('success-border');
                }, 2000);
            }
        });

        // 下载结果
        downloadBtn.addEventListener('click', () => {
            if (!textOutput.value.trim()) {
                DevToolsUtils.showToast('没有可下载的内容', 'error');
                return;
            }

            const mode = document.querySelector('input[name="mode"]:checked').value;
            const extension = mode === 'csv' ? 'csv' : 'txt';
            const filename = `deduplicated_text_${new Date().getTime()}.${extension}`;
            
            const blob = new Blob([textOutput.value], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            DevToolsUtils.showToast('文件下载已开始', 'success');
        });

        // 键盘快捷键
        textInput.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                processBtn.click();
            }
        });

        // 文件拖拽上传
        textInput.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.stopPropagation();
            textInput.classList.add('border-blue-400', 'bg-blue-50');
        });

        textInput.addEventListener('dragleave', (e) => {
            e.preventDefault();
            e.stopPropagation();
            textInput.classList.remove('border-blue-400', 'bg-blue-50');
        });

        textInput.addEventListener('drop', (e) => {
            e.preventDefault();
            e.stopPropagation();
            textInput.classList.remove('border-blue-400', 'bg-blue-50');
            
            const files = Array.from(e.dataTransfer.files);
            if (files.length > 0) {
                const file = files[0];
                if (file.type === 'text/plain' || file.type === 'text/csv' || file.name.endsWith('.txt') || file.name.endsWith('.csv')) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        textInput.value = e.target.result;
                        updateInputStats();
                        
                        // 根据文件类型自动选择模式
                        if (file.name.endsWith('.csv')) {
                            document.querySelector('input[name="mode"][value="csv"]').checked = true;
                            textOptions.style.display = 'none';
                            csvOptions.style.display = 'block';
                        }
                    };
                    reader.readAsText(file);
                } else {
                    DevToolsUtils.showToast('请选择文本文件或CSV文件', 'error');
                }
            }
        });

        // 初始化图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
};